package cn.bo.cloud.common.redis.listener;

import cn.bo.cloud.common.redis.handle.RedisKeyExpirationProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听失效的key，redis清理key后触发onMessage()
 * 该类为监听，具体业务请不要在该类中编写，请自行实现{@link RedisKeyExpirationProcessor}接口。
 * 监听捕获信息后会调用所有RedisKeyExpirationProcessor接口的实现类依次通知，
 * 因此，**请注意不要重复对同一个key进行相同的处理，可能会带来未知风险。**
 *
 *
 * @see RedisKeyExpirationProcessor
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private List<RedisKeyExpirationProcessor> redisKeyExpirationProcessorList;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        for (RedisKeyExpirationProcessor expirationProcessor : redisKeyExpirationProcessorList){
            expirationProcessor.onMessage(message, pattern);
        }
    }

}
